# encoding:utf8
"""
@File        : dot_dict.py
@Time        : 2019/7/11 11:25
@Author      : zhaoy
@Email       : zhaoyao@shandiangou.cc
@Description : 
"""


class dotdictify(dict):
    def __init__(self, value=None):
        if value is None:
            pass
        elif isinstance(value, dict):
            for key in value:
                self.__setitem__(key, value[key])
        else:
            raise TypeError('expected dict')
        super(dotdictify, self).__init__()

    def __setitem__(self, key, value):
        if '.' in key:
            myKey, restOfKey = key.split('.', 1)
            target = self.setdefault(myKey, dotdictify())
            if not isinstance(target, dotdictify):
                raise KeyError('cannot set "%s" in "%s" (%s)' % (restOfKey, myKey, repr(target)))
            target[restOfKey] = value
        else:
            if isinstance(value, dict) and not isinstance(value, dotdictify):
                value = dotdictify(value)
            dict.__setitem__(self, key, value)

    def __getitem__(self, key):
        if '.' not in key:
            return dict.__getitem__(self, key)
        myKey, restOfKey = key.split('.', 1)
        target = dict.__getitem__(self, myKey)
        if not isinstance(target, dotdictify):
            raise KeyError('cannot get "%s" in "%s" (%s)' % (restOfKey, myKey, repr(target)))
        return target[restOfKey]

    def __contains__(self, key):
        if '.' not in key:
            return dict.__contains__(self, key)
        myKey, restOfKey = key.split('.', 1)
        target = dict.__getitem__(self, myKey)
        if not isinstance(target, dotdictify):
            return False
        return restOfKey in target

    def setdefault(self, key, default=None):
        if key not in self:
            self[key] = default
        return self[key]

    __setattr__ = __setitem__
    __getattr__ = __getitem__


dct = {"resultCode": "0", "resultMsg": "", "resultData": {
    "poiInfo": {"districtCode": "02902", "provName": "陕西省", "townCode": "0290299", "cityCode": "029", "fromEvt": "0",
                "poiTypeCode": "141201", "locLng": 108.984598, "cityName": "西安市", "outPoiStatus": "Y", "poiFrom": "2",
                "hasStore": "nearby", "poiId": 1037100140096029, "poiTypeTag": "", "townName": "全区",
                "address": "咸宁西路28号", "districtName": "碑林区", "provCode": "250", "poiName": "西安交通大学(兴庆校区)",
                "locLat": 34.246033, "hasStoreCnt": 3, "invalid": "0", "outPoiId": "B001D06LLT"}}}
dot_dct = dotdictify(dct)
print(dot_dct.resultData.poiInfo.poiId)

import json

aa = json.dumps(dot_dct)
print(aa)
